package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hangzhou.xyj.R;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.event.CorrectRespEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.type.ECorrectType;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.net.handler.UpdateCertificationHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.http.okhttp.OkHttpClientManager;
import com.hangzhou.xyj.net.request.UpdateCertificationReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.listener.CheckLoginListener;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.multiimageselector.MultiImageSelectorActivity;
import com.hangzhou.xyj.ui.widget.views.MyImageView;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.API;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Request;

/**
 * Created by Administrator on 2016/1/13.
 */
public class MyProfessionAuthenActivity extends BaseActivity {
    public static final int REQUEST_CODE_IMAGE_IDCARD = 1;
    public static final int REQUEST_CODE_IMAGE_WORK = 2;

    EditText mEtName;//名字
    EditText mEtTeacher;//师承
    //    EditText mEtProfess;//剧种
    EditText mEtGroupName;//所属院团
    EditText mEtIntroduce;//简介

    MyTextView mTvIdCardTip;//身份证提示文字
    MyTextView mTvWorkImgTip;//职称提示文字
    MyImageView mIvIdcardDefImg;//身份证默认图片
    MyImageView mIvWorkImgDefImg;//职称默认图片
    CircleImageView mCivIdCard;//身份证
    CircleImageView mCivWorkImg;//职称
    RelativeLayout mLlIdcard;//身份证区域
    RelativeLayout mLlWorkImg;//职称区域
    RelativeLayout mRlChoose;//选择剧种区域
    MyTextView mTvCatType;//剧种


    String mIdcardFilePath;//身份证的本地路径
    String mWorkImgPath;//职称的本地路径
    String mIdCardServerPath;//身份证在服务器的路径
    String mWorkImgServerPath;//身份证在服务器的路径


    String mName;//名字
    String mTeacher;//师承
    String mProfess;//剧种
    String mGroupName;//所属院团
    String mIntroduce;//简介不能为空
    String mCatId;//剧种Id


    public boolean checkInput() {
        mName = mEtName.getText().toString().trim();//名字
        mIntroduce = mEtIntroduce.getText().toString().trim();//简介
        mTeacher = mEtTeacher.getText().toString().trim();//师承
//        mProfess = mEtProfess.getText().toString().trim();//行当

        mGroupName = mEtGroupName.getText().toString().trim();//所属院团
        if (StringUtil.isEmpty(mName)) {
            ToastUtil.show("名字不能为空");
            return false;
        }
        if (!PublicUtil.checkStrLength(mName, 15)) {
            ToastUtil.show("名字长度不能超过15个字，请检查！");
            return false;
        }
        if (StringUtil.isEmpty(mIntroduce)) {
            ToastUtil.show("简介不能为空");
            return false;
        }
        if (StringUtil.isEmpty(mTeacher)) {
            ToastUtil.show("师承不能为空");
            return false;
        }
        if (!PublicUtil.checkStrLength(mTeacher, 15)) {
            ToastUtil.show("师承长度不能超过15个字，请检查！");
            return false;
        }
        if (StringUtil.isEmpty(mProfess)) {
            ToastUtil.show("剧种不能为空");
            return false;
        }

        if (StringUtil.isEmpty(mGroupName)) {
            ToastUtil.show("所属院团不能为空");
            return false;
        }
        if (!PublicUtil.checkStrLength(mGroupName, 15)) {
            ToastUtil.show("所属院团长度不能超过15个字，请检查！");
            return false;
        }
        if (StringUtil.isEmpty(mIdcardFilePath)) {
            ToastUtil.show("请选择身份证正面！");
            return false;
        }
        if (StringUtil.isEmpty(mWorkImgPath)) {
            ToastUtil.show("请上传职称正面！");
            return false;
        }
        return true;
    }

    @Override
    public void initDatas() {
        registerEventBus();
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_profession_authen);
    }

    @Override
    public void initListeners() {
        mLlIdcard.setOnClickListener(new CheckLoginListener() {
            @Override
            public void onClickView(View v) {
                Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                // 是否显示调用相机拍照
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大图片选择数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                IntentManager.getInstance().goImageSelectorActivity(MyProfessionAuthenActivity.this, intent, REQUEST_CODE_IMAGE_IDCARD);
            }
        });

        mLlWorkImg.setOnClickListener(new CheckLoginListener() {
            @Override
            public void onClickView(View v) {
                Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                // 是否显示调用相机拍照
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大图片选择数量
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                IntentManager.getInstance().goImageSelectorActivity(MyProfessionAuthenActivity.this, intent, REQUEST_CODE_IMAGE_WORK);
            }
        });

        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                //校验不通过
                if (!checkInput()) {
                    return;
                }
                showLoadingDialog();
                uploadFile(mIdcardFilePath);
                uploadFile(mWorkImgPath);
            }
        });
        mRlChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, DramaCategoryListActivity.class);
                intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_ADD_GROUP.getValue());
                intent.putExtra(DataKey.TITLE, "选择剧种");
                IntentManager.getInstance().goActivity(mContext, intent);
            }
        });
    }

    @Override
    public void initTop() {
        enableTitle(true, "认证");
        enableRightNav(true, "确定");
    }

    @Override
    public void initViews() {
        mEtName = findView(R.id.et_name);//名字
        mEtIntroduce = findView(R.id.et_introduce);//简介
        mEtTeacher = findView(R.id.et_teacher);//师承
        mTvCatType = findView(R.id.mtv_group_type);//剧种
        mEtGroupName = findView(R.id.et_group_name);//所属院团
        mRlChoose = findView(R.id.rl_choose);//选择剧种
        mTvIdCardTip = findView(R.id.mtv_id_card_tip);//身份证提示文字
        mTvWorkImgTip = findView(R.id.mtv_work_img_tip);//职称提示文字
        mIvIdcardDefImg = findView(R.id.miv_id_card_def_img);//身份证默认图片
        mIvWorkImgDefImg = findView(R.id.miv_work_img_def_img);//职称默认图片
        mCivIdCard = findView(R.id.civ_id_card);//身份证
        mCivWorkImg = findView(R.id.civ_work_img);//职称

        mLlIdcard = findView(R.id.ll_idcard);//身份证区域
        mLlWorkImg = findView(R.id.ll_work_img);//职称区域
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMAGE_IDCARD && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            mIdcardFilePath = path.get(0);
            mIvIdcardDefImg.setVisibility(View.GONE);
            mTvIdCardTip.setVisibility(View.GONE);
            ImageLoader.getInstance().displayImage("file:///" + mIdcardFilePath, mCivIdCard);
            mCivIdCard.setVisibility(View.VISIBLE);
        }

        if (requestCode == REQUEST_CODE_IMAGE_WORK && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            mWorkImgPath = path.get(0);
            mIvWorkImgDefImg.setVisibility(View.GONE);
            mTvWorkImgTip.setVisibility(View.GONE);
            ImageLoader.getInstance().displayImage("file:///" + mWorkImgPath, mCivWorkImg);
            mCivWorkImg.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 选择圈子类别 事件订阅
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/22 10:08
     */
    @Subscribe
    public void onEventMainThread(CorrectRespEvent event) {
        switch (ECorrectType.valueOf(event.getTag())) {
            case CHOOSE:
                mProfess = event.getValue();
                mCatId = event.getValue2();
                mTvCatType.setText(mProfess);
                break;
        }
    }


    /**
     * 单个文件上传
     *
     * @param
     * @return 返回上传到服务器以后，文件在服务器上的地址
     * @author yaohuix
     * @date 2016/3/18 13:38
     */
    public void uploadFile(String fileName) {
        try {
            OkHttpClientManager.getInstance().postAsyn(API.FILE_UPLOAD, new OkHttpClientManager.ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    ToastUtil.show("上传出错!");
                    count++;
                }

                @Override
                public void onResponse(String response) {
                    count++;
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    boolean isSuccess = "success".equals(jsonObject.get("msg").getAsString()) ? true : false;
                    if (count == 1 && isSuccess) {//第一张上传成功之后回调
                        mIdCardServerPath = jsonObject.get("data").getAsString();
                    }
                    if (count == 2 && isSuccess) {//第二张上传成功之后回调
                        mWorkImgServerPath = jsonObject.get("data").getAsString();
                        //提交认证信息
                        UpdateCertificationReq updateCertificationReq = new UpdateCertificationReq(Integer.valueOf(CommonPreferences.getUserId(mContext)),
                                mName, mIdCardServerPath, mWorkImgServerPath, mGroupName, mTeacher, mIntroduce, mCatId);
                        HttpLoader.getInstance().sendRequest(new UpdateCertificationHandler(updateCertificationReq, new MyHttpResponseListener() {
                            @Override
                            public void onSuccess(Object model) {
                                super.onSuccess(model);
                                hideLoadingDialog();
                                ToastUtil.show("资料上传成功，请等待审核结果！");
                                CorrectRespEvent event = new CorrectRespEvent();
                                event.setTag(ECorrectType.AUTHEN.getValue());
                                EventBusUtil.postEvent(event);
                                closeActivity();
                            }
                        }, 0));
                    }
                }
            }, new File(fileName), "file");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
